package com.ihr360.payroll.model.dto.salary.tax;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.common.collect.Lists;
import com.ihr360.commons.model.ITemporalEntity;
import com.ihr360.commons.model.entity.NumberIdWithTime;
import com.ihr360.payroll.model.vo.SalaryTaxRuleVO;
import org.springframework.beans.BeanUtils;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/** 税率 */
@Entity
public class SalaryTax extends NumberIdWithTime<Long> implements ITemporalEntity {

    private static final long serialVersionUID = -7547175034106583325L;

    /** 生效日期 */
    @Column(nullable = false)
    private Date effectiveAt;

    /** 失效日期 */
    private Date invalidAt;

    /** 固定税率/超额累进 */
    private boolean fixed = false;

    /** 税率规则 */
    @OneToMany(mappedBy = "salaryTax", cascade = CascadeType.ALL, orphanRemoval = true,fetch = FetchType.EAGER)
    @OrderBy("floor")
    private List<SalaryTaxRule> rules = new ArrayList<>();

    /** 所属税率表 */
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(nullable = false)
    private SalaryTaxTable taxTable;

    @Column(columnDefinition = "bit(1) default 0")
    private boolean embedded;

    public boolean isFixed() {
        return fixed;
    }

    public void setFixed(boolean fixed) {
        this.fixed = fixed;
    }

    public List<SalaryTaxRule> getRules() {
        return rules;
    }
    @JsonIgnore
    public List<SalaryTaxRuleVO> getRuleVOs() {
        if (org.apache.commons.collections.CollectionUtils.isEmpty(rules)) {
            return Collections.emptyList();
        }
        List<SalaryTaxRuleVO> salaryTaxRuleVOS = Lists.newArrayListWithCapacity(rules.size());
        rules.forEach(rule -> {
            SalaryTaxRuleVO salaryTaxTypeVO = new SalaryTaxRuleVO();
            BeanUtils.copyProperties(rule, salaryTaxTypeVO);
            salaryTaxRuleVOS.add(salaryTaxTypeVO);
        });
        return salaryTaxRuleVOS;
    }


    public void setRules(List<SalaryTaxRule> rules) {
        this.rules = rules;
    }

    public SalaryTaxTable getTaxTable() {
        return taxTable;
    }

    public void setTaxTable(SalaryTaxTable taxTable) {
        this.taxTable = taxTable;
    }

    @Override
    public java.util.Date getEffectiveAt() {
        return effectiveAt;
    }

    @Override
    public java.util.Date getInvalidAt() {
        return invalidAt;
    }

    @Override
    public void setEffectiveAt(Date effectiveAt) {
        this.effectiveAt = effectiveAt;
    }

    @Override
    public void setInvalidAt(Date invalidAt) {
        this.invalidAt = invalidAt;
    }
}
